import debounce from 'lodash.debounce';

export default function createSearchOptions(config = {}) {
    let { apiurl, resultKey, searchWordParam, defaultSearchType, isPagination = false, pageSize = 10, loadOnCreation = true } = config || {};

    let data = {
        searchWord: '',
    }

    let _extraParams = null;

    if (defaultSearchType) {
        data.searchType = defaultSearchType;
    }

    let options = {
        data() {
            return data
        },
        methods: {
            async search(extraParams) {
                if (extraParams) {
                    _extraParams = extraParams;
                }

                let params = {
                    [searchWordParam ? searchWordParam : this.searchType]: this.searchWord,
                    ..._extraParams
                };

                // if (extraParams) {
                //     if (Array.isArray(extraParams)) {
                //         for (const param of extraParams) {
                //             params[param] = this[param] || undefined;
                //         }
                //     } else if (typeof extraParams === 'string') {
                //         params[extraParams] = this[extraParams] || undefined;
                //     }
                // }

                if (isPagination) {
                    params.pageSize = this.pageSize;
                    params.pageCurrent = this.currentPage;

                    let res = await this.$get(apiurl, params);
                    this[resultKey] = Object.freeze(res.records);
                    this.total = res.total;
                } else {
                    this[resultKey] = Object.freeze(await this.$get(apiurl, params));
                }

            }
        },
        watch: {
            searchWord: {
                handler: debounce(function () {
                    if (this.currentPage) {
                        this.currentPage = 1;
                    }
                    this.search();
                }, 800)
            },

        }
    }

    if (isPagination) {
        data.currentPage = 1;
        data.pageSize = pageSize;
        data.total = 0;
        options.methods.onCurrentChange = function () {
            this.search();
        }
    }

    if (loadOnCreation) {
        options.created = function () {
            this.search();
        }
    }

    return options;
}
